﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Galoap
{
    partial class Answer
    {
        public Answer() : base()
        {
        }

        public static T CreateAnswer<T>(Question question, GameSession gameSession, String jsonAnswer) where T : Answer, new()
        {
            T retAnswer = new T();
            retAnswer.Initialize(jsonAnswer);
            // question.Answer.Load();
            
            bool isknown = false;
            try
            {
                if(question.Answer.Count <= 0)    
                    question.Answer.Load();
                IEnumerable<T> listOfAnswers = question.Answer.OfType<T>().ToList<T>();
                foreach (Answer a in listOfAnswers)
                {
                    isknown = isknown || a.Truth;
                }
                retAnswer = listOfAnswers.Where(a => a.CompareData(retAnswer)).First();
                retAnswer.Counter++;
            }
            catch (InvalidOperationException)
            {
                retAnswer.Counter = 1;
                GaloapDatabase.Database.AddToAnswer(retAnswer);
                question.Answer.Add(retAnswer);
            }

            gameSession.UpdateUserRanking(retAnswer, isknown);
            gameSession.Add(retAnswer);
            return retAnswer;
        }

        protected abstract void Initialize(string json);

        /// <summary>
        /// Adds this to the database
        /// </summary>
        public void AddAnswerToDB()
        {
            GaloapDatabase.Database.AddToAnswer(this);
            GaloapDatabase.Database.SaveChanges();
        }

        /// <summary>
        /// Saves the current state of this in the database
        /// </summary>
        public void Save()
        {
            GaloapDatabase.Database.SaveChanges();
        }
    }
}
